package ourfilter;

import interfaces.Readable;
import interfaces.Writeable;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.StreamCorruptedException;
import java.sql.Timestamp;
import java.util.Date;

import pipes.Pipe;
import TransferObjekts.Line;

public class Source implements Readable<Line>, Runnable {

	private String path;
	private int lineNumber = 0;
	private Writeable<Line> outPipe;

	public Source(String path, Pipe<Line> outPipe) {
		this.path = path;
		outPipe.setIn(this);
		this.outPipe = outPipe;
	}

	private BufferedReader br = null;

	@Override
	public Line read() throws StreamCorruptedException {
		String line = "";
		try {
			if (br == null) {
				br = new BufferedReader(new FileReader(this.path));
			}
			line = br.readLine();
			lineNumber++;
		} catch (IOException io) {
			io.printStackTrace();
		}

		return new Line(line, lineNumber);
	}

	@Override
	public void run() {
		System.out.println("started " + new Timestamp(new Date().getTime()));
		Line line = null;
		try {
			do {
				line = this.read();
				try {
					outPipe.write(line);
				} catch (StreamCorruptedException e) {
					e.printStackTrace();
				}
			} while (line.getLine() != null);
		} catch (StreamCorruptedException e1) {
			e1.printStackTrace();
		}
		System.out.println("finished " + new Timestamp(new Date().getTime()));
	}
}
